Stacks

Stacks are easy to implement in JavaScript. Use an array with a "top" pointer. To try this stack applet out, just start typing. Press [Push] to store each value onto the stack.

: STACK


Discussion

Stacks provide a good example of an array application; they are easy to implement using JavaScript primitives. As an exercise for the reader, inspect the following code and figure out where the "popped" value goes.
// Show the Stack
function showstack()
{
    var answer=""
    for (var i = 0; i < sktop; i++) answer = stack[i] + ": " + answer
    document.forms[0].stack.value = answer
    document.forms[0].input.focus();document.forms[0].input.select()
}

// Push value onto stack
function push()
{
    stack[sktop]=""+document.forms[0].input.value
    sktop++ // increase top
    showstack()
}

// Pop value off of stack
function pop()
{
    if (sktop > 0) 
    {
        document.forms[0].input.value=""+stack[sktop-1]
        sktop -= 1 // decrease top
    }
    else alert("Stack is empty!")
    showstack()
}
Copyright ©1998 by Charles River Media, All Rights Reserved